package zcj.stu.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//此组件用来实现 微信小程序和管理后台实现通信
@Component
@Slf4j
@ServerEndpoint("/{identity}")
public class MyWebSocket {
    /**
     * 存放所有在线的客户端 [identity, session]
     */
    private static final Map<String, Session> clients = new ConcurrentHashMap<>();

    public void sendMessage(String identity, String message) {
        if (!clients.containsKey(identity)) {
            log.error("未找到指定客户端{}的websocket连接!", identity);
            return;
        }
        Session session = clients.get(identity);
        try {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("准备向客户端程序{}发送消息:{}", identity, message);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        Map map = (Map) JSON.parse(message);
        Object identity = map.get("identity");
        if (map != null && "admin".equals(identity)) {
            sendMessage((String) map.get("identityTo"),(String) map.get("msg"));
        } else {
            sendMessage("admin", (String) map.get("msg"));
        }
    }

    @OnOpen
    public void onOpen(@PathParam("identity") String identity, Session session) {
        session.setMaxIdleTimeout(0);
        clients.put(identity, session);
        log.info("客户端程序{}建立连接成功!------>当前在线人数为：{}", identity, getOnlineCount());
    }

    @OnClose
    public void onClose(@PathParam("identity")String identity, Session session) {
        System.out.println(identity+"------------------");
        if (!clients.containsKey(identity)) {
            log.warn("客户端程序{}没有连接,无需断开连接", identity);
            return;
        }
        clients.remove(identity);
        log.info("客户端程序{}断开连接成功!------>当前在线人数为：{}", identity,getOnlineCount());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("连接{}发生错误!", session.getId());
        throwable.printStackTrace();
    }

    public boolean sessionIsOpen(String sessionId) {
        return clients.get(sessionId).isOpen();
    }

    public synchronized int getOnlineCount() {
        return clients.size();
    }
}
